import { Button, Tabs, Input, Image, Popconfirm, Tag } from "antd";
import {
  FieldTimeOutlined,
  CloseCircleOutlined,
  CheckCircleOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import CommonPage from "@/components/page/CommonPage";

import styled from "styled-components";
import DeleteOne from "@/components/svg/action-slot-icon/Delete_One";
import Agree from "@/components/svg/action-slot-icon/Agree";
import CrudTable from "@/components/table/CrudTable";
import QueryBarItem from "@/components/query-bar/QueryBarItem";
import { useEffect, useRef } from "react";
import useMyContext from "@/hooks/useContext";
import useCRUD from "@/hooks/useCRUD";
import useGetState from "@/hooks/useGetState";
import { convertImgUrl } from "@/utils/MyFun";
import { formatDate } from "@/utils/common/common";
import {
  deleteMessages,
  getMessages,
  updateMessageReview,
} from "@/api/message";
const Styled = styled.div``;

const LevelMsg = () => {
  const $table = useRef();
  const { messageApi } = useMyContext();
  const { handleDelete, tableSelections, setTableSelections } = useCRUD({
    name: "留言",
    refresh: () => $table.current.handleSearch(),
    doDelete: deleteMessages,
  });
  const [extraParams, setExtraparams, getExtraparams] = useGetState({});
  const [queryItems, setQueryItems, getQueryItems] = useGetState({});

  const Tabitems = [
    {
      key: "all",
      label: "全部",
    },
    {
      key: "has_review",
      label: "通过",
    },
    {
      key: "not_review",
      label: "审核中",
    },
  ];
  const columns = [
    {
      title: "头像",
      key: "avatar",
      dataIndex: "avatar",
      width: 50,
      align: "center",
      render: (text, record, index) => {
        return (
          <Image
            style={{ height: "50px", borderRadius: "3px" }}
            src={convertImgUrl(record.avatar)}
            fallback="http://dummyimage.com/400x400"
          />
        );
      },
    },
    {
      title: "留言人",
      key: "nickname",
      dataIndex: "nickname",
      width: 60,
      align: "center",
      ellipsis: true,
    },
    {
      title: "留言内容",
      key: "content",
      dataIndex: "content",
      width: 120,
      align: "center",
    },
    {
      title: "IP 地址",
      key: "ip_address",
      dataIndex: "ip_address",
      width: 70,
      align: "center",
      ellipsis: true,
    },
    {
      title: "IP 来源",
      key: "ip_source",
      dataIndex: "ip_source",
      width: 70,
      align: "center",
      ellipsis: true,
      render(text, record, index) {
        return <span>{record.ip_source || "未知"}</span>;
      },
    },
    {
      title: "留言时间",
      key: "created_at",
      align: "center",
      width: 80,
      render(text, record, index) {
        return (
          <Button
            type="link"
            icon={<FieldTimeOutlined />}
            size="small"
            style={{ color: "#333" }}
          >
            {formatDate(record.update_at)}
          </Button>
        );
      },
    },
    {
      title: "状态",
      key: "is_review",
      width: 50,
      align: "center",
      render(text, record, index) {
        return (
          <Tag color={record.is_review ? "success" : "error"}>
            {record.is_review ? "通过" : "审核中"}
          </Tag>
        );
      },
    },
    {
      title: "操作",
      key: "actions",
      width: 100,
      align: "center",
      fixed: "right",
      render(text, record, index) {
        return (
          <>
            {record.is_review ? (
              <Button
                type="primary"
                icon={<CloseCircleOutlined />}
                style={{
                  marginRight: "5px",
                  backgroundColor: "gold",
                }}
                onClick={async () => {
                  handleUpdateReview([record.id], 0);
                }}
              >
                撤下
              </Button>
            ) : (
              <Button
                type="primary"
                icon={<CheckCircleOutlined />}
                style={{
                  marginRight: "5px",
                }}
                onClick={() => {
                  handleUpdateReview([record.id], 1);
                }}
              >
                通过
              </Button>
            )}
            <Popconfirm
              title="确认删除该文章吗"
              description="删除后可在回收站中查看"
              onConfirm={() => {
                handleDelete([record.id]);
              }}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="primary"
                icon={<DeleteOutlined />}
                style={{ backgroundColor: "#D03050FF" }}
              >
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  const handleChangeTab = (value) => {
    // eslint-disable-next-line default-case
    switch (value) {
      case "all":
        setExtraparams({ is_review: null });
        break;
      case "has_review": // 通过
        setExtraparams({ is_review: 1 });
        break;
      case "not_review": // 审核中
        setExtraparams({ is_review: 0 });
        break;
    }
    $table.current.handleSearch();
  };

  function updateQueryItems(newQueryItems) {
    console.log("更新query", newQueryItems);
    setQueryItems(newQueryItems);
  }

  // 修改评论审核: is_review 0-撤下审核, 1-通过审核
  async function handleUpdateReview(ids, is_review) {
    if (ids.length === 0) {
      messageApi.info("请选择要审核的数据");
      return;
    }
    try {
      await updateMessageReview({ ids, is_review });
      messageApi.success(is_review ? "审核成功" : "撤下成功");
      $table.current.handleSearch();
    } catch (error) {
      console.log(error);
      messageApi.error("审核失败");
    }
  }
  useEffect(() => {
    $table.current.handleSearch();
  }, []);

  return (
    <Styled>
      <CommonPage title="留言管理">
        <div className="action-slot" slot="action">
          <Button
            type="primary"
            icon={<DeleteOne />}
            danger
            onClick={() => {
              handleDelete(tableSelections);
            }}
          >
            批量删除
          </Button>
          <Button
            type="primary"
            icon={<Agree />}
            style={{ backgroundColor: "green" }}
            onClick={() => {
              handleUpdateReview(tableSelections, 1);
            }}
          >
            批量通过
          </Button>
        </div>
        {/* 导航栏 */}
        <Tabs
          defaultActiveKey="all"
          items={Tabitems}
          onChange={handleChangeTab}
        />
        <CrudTable
          ref={$table}
          columns={columns}
          getExtraparams={getExtraparams}
          queryItems={queryItems}
          updateQueryItems={updateQueryItems}
          getQueryItems={getQueryItems}
          setTableSelections={setTableSelections}
          getData={getMessages}
        >
          <div className="queryBar-slot flex label-ml-15" slot="queryBar">
            <QueryBarItem label="用户" labelWidth={40} contentWidth={180}>
              <Input
                placeholder="请输入用户昵称"
                allowClear
                value={queryItems.nickname}
                onChange={(e) => {
                  setQueryItems({
                    ...queryItems,
                    nickname: e.target.value,
                  });
                }}
              />
            </QueryBarItem>
          </div>
        </CrudTable>
      </CommonPage>
    </Styled>
  );
};

export default LevelMsg;
